package me.key.iwifimanager2;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DecimalFormat;

import me.key.iwifimanager2.util.Global;
import me.key.iwifimanager2.util.UtilTool;

import static android.util.Log.e;

public class MainActivity extends Activity implements OnItemSelectedListener, OnTouchListener {

    private int i = 0; //global
    //IP address
    //ip地址
    private EditText et_ip;
    //Port value
    //端口
    private EditText et_port;

    //Spinner array
    private Spinner[] sSpinners = new Spinner[8];

    private Spinner sp1;
    private Spinner sp2;
    private Spinner sp3;
    private Spinner sp4;
    private Spinner sp5;
    private Spinner sp6;
    private Spinner sp7;
    private Spinner sp8;
    //Connect button
    private Button btnConnect;

    //All value button
    private Button btn_1;
    private Button btn_2;
    private Button btn_3;
    private Button btn_4;
    private Button btn_5;
    private Button btn_6;
    private Button btn_7;
    private Button btn_8;
    //private Button btnRun;

    //All time button
    private Button btn_t1;
    private Button btn_t2;
    private Button btn_t3;
    private Button btn_t4;
    private Button btn_t5;
    private Button btn_t6;
    private Button btn_t7;
    private Button btn_t8;

    private Button btnBatteryVolts;
    private Button btnACVolts;

    //Button array
    private Button[] btns = new Button[8];//Btn1-8
    //Button time array
    private Button[] btn_times = new Button[8];
    //Is highlight or nor array
    private boolean[] isHighs = new boolean[8];//HighLight true, or false
    //Need to send datas array
    byte[] datas = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};//datas[0] the value, datas[1] the mark
    //Set spingner mark
    int[] spvalues = new int[8];//"T","M","L"
    //Need to set spner datas
    byte[] spdatas = new byte[3];//0x01,0x02,0x03
    //Delay times array
    int[] times = new int[8];
    //About Socket
    //Save the instance
    private SharedPreferences sharedPreferences;
    //	private InetSocketAddress isa = null;
    //接收到的数据
    public static int receivedata = 0 & 0xFF;
    //wifi链接线程
    private SocketThread socketThread;
    //是否连接上wifi
    private boolean isConnect = false;
    private EditText et_First, et_Second;
    private double batteryVoltsValue = 0.0, ACVoltsValue = 0.0;
    //一级电压报警值 二级电压报警值
    private int alarmVoltage1, alarmVoltage2;
    private DecimalFormat batteryVoltsFormat, ACVoltsFormat;
    private CountDownTimer countDownTimer;
    private String first, second;
    private Context context;
    //wifi名字
    private TextView tvSSID;
    private  WifiManager wifiManager;
    //修改按钮名字
    private String changeName1, changeName2, changeName3, changeName4;
    public static byte[] voltageSend = new byte[8];


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        batteryVoltsFormat = new DecimalFormat("######0.00");
        ACVoltsFormat = new DecimalFormat("######0.0");
        context = this;
        initButtons();
        initSpinners();
        initDatas();
         wifiManager = (WifiManager) this.getApplicationContext().getSystemService(WIFI_SERVICE);
        registerReceiver();
    }

    private void initDatas() {
        // TODO Auto-generated method stub
        //发送数据的头帧
        datas[0] = (byte) 0xA9;
        //关闭设备信号（接收到我设备给手机发送的报警判断位的二级报警，计时5分钟后发出的关闭设备信号0x01，默认的发送0x00）
        datas[7] = (byte) 0x00;


        spdatas[0] = (byte) 0x01;
        spdatas[1] = (byte) 0x02;
        spdatas[2] = (byte) 0x03;


        btns[0] = btn_8;
        btns[1] = btn_7;
        btns[2] = btn_6;
        btns[3] = btn_5;
        btns[4] = btn_4;
        btns[5] = btn_3;
        btns[6] = btn_2;
        btns[7] = btn_1;

        btn_times[0] = btn_t1;
        btn_times[1] = btn_t2;
        btn_times[2] = btn_t3;
        btn_times[3] = btn_t4;
        btn_times[4] = btn_t5;
        btn_times[5] = btn_t6;
        btn_times[6] = btn_t7;
        btn_times[7] = btn_t8;

        for (i = 0; i < 8; i++) {
            isHighs[i] = false;
            btns[i].setBackgroundColor(Color.GRAY);
            times[i] = sharedPreferences.getInt("time" + i, 0);
            spvalues[i] = sharedPreferences.getInt("sp" + i, 0);
            btn_times[i].setText(times[i] + "s");
            sSpinners[i].setSelection(spvalues[i]);
        }
        et_ip.setText(sharedPreferences.getString("ip", "10.10.100.254"));
        et_port.setText(sharedPreferences.getString("port", "8899"));
        first = sharedPreferences.getString("first", "0");
        second = sharedPreferences.getString("second", "0");
        changeName1 = sharedPreferences.getString("changeName1", "ACC 1");
        changeName2 = sharedPreferences.getString("changeName2", "ACC 2");
        changeName3 = sharedPreferences.getString("changeName3", "ACC 3");
        changeName4 = sharedPreferences.getString("changeName4", "ACC 4");
        getFirstSencondValue(first, second);

        btn_5.setText(changeName1);
        btn_6.setText(changeName2);
        btn_7.setText(changeName3);
        btn_8.setText(changeName4);


    }

    private void initSpinners() {
        // TODO Auto-generated method stub
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Global.MODE);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp1.setAdapter(adapter);
        sp2.setAdapter(adapter);
        sp3.setAdapter(adapter);
        sp4.setAdapter(adapter);
        sp5.setAdapter(adapter);
        sp6.setAdapter(adapter);
        sp7.setAdapter(adapter);
        sp8.setAdapter(adapter);
        sp1.setOnItemSelectedListener(this);
        sp2.setOnItemSelectedListener(this);
        sp3.setOnItemSelectedListener(this);
        sp4.setOnItemSelectedListener(this);
        sp5.setOnItemSelectedListener(this);
        sp6.setOnItemSelectedListener(this);
        sp7.setOnItemSelectedListener(this);
        sp8.setOnItemSelectedListener(this);
    }

    /**
     * Init the widget
     */
    private void initButtons() {
        // TODO Auto-generated method stub
        sharedPreferences = getSharedPreferences("mode", MODE_PRIVATE);
        //wifi链接按钮
        btnConnect = (Button) findViewById(R.id.btn_connect);
        //ip输入框
        et_ip = (EditText) findViewById(R.id.et_ip);
        //端口输入框
        et_port = (EditText) findViewById(R.id.et_port);

        sp1 = (Spinner) findViewById(R.id.sp_1);
        sp2 = (Spinner) findViewById(R.id.sp_2);
        sp3 = (Spinner) findViewById(R.id.sp_3);
        sp4 = (Spinner) findViewById(R.id.sp_4);
        sp5 = (Spinner) findViewById(R.id.sp_5);
        sp6 = (Spinner) findViewById(R.id.sp_6);
        sp7 = (Spinner) findViewById(R.id.sp_7);
        sp8 = (Spinner) findViewById(R.id.sp_8);

        sSpinners[0] = sp1;
        sSpinners[1] = sp2;
        sSpinners[2] = sp3;
        sSpinners[3] = sp4;
        sSpinners[4] = sp5;
        sSpinners[5] = sp6;
        sSpinners[6] = sp7;
        sSpinners[7] = sp8;
        //run
        btn_1 = (Button) findViewById(R.id.btn_1);
        //Start
        btn_2 = (Button) findViewById(R.id.btn_2);
        //ECONOMY MODE
        btn_3 = (Button) findViewById(R.id.btn_3);
        //OUTLETO
        btn_4 = (Button) findViewById(R.id.btn_4);
        btn_5 = (Button) findViewById(R.id.btn_5);
        btn_6 = (Button) findViewById(R.id.btn_6);
        btn_7 = (Button) findViewById(R.id.btn_7);
        btn_8 = (Button) findViewById(R.id.btn_8);
        //btnRun= (Button) findViewById(R.id.btn_run);

        btnBatteryVolts = (Button) findViewById(R.id.btn_allon);
        btnACVolts = (Button) findViewById(R.id.btn_ac);

        btn_1.setOnTouchListener(this);
        btn_2.setOnTouchListener(this);
        btn_3.setOnTouchListener(this);
        btn_4.setOnTouchListener(this);
        btn_5.setOnTouchListener(this);
        btn_6.setOnTouchListener(this);
        btn_7.setOnTouchListener(this);
        btn_8.setOnTouchListener(this);

        //btnRun.setOnTouchListener(this);

        btn_t1 = (Button) findViewById(R.id.btn_t1);
        btn_t2 = (Button) findViewById(R.id.btn_t2);
        btn_t3 = (Button) findViewById(R.id.btn_t3);
        btn_t4 = (Button) findViewById(R.id.btn_t4);
        btn_t5 = (Button) findViewById(R.id.btn_t5);
        btn_t6 = (Button) findViewById(R.id.btn_t6);
        btn_t7 = (Button) findViewById(R.id.btn_t7);
        btn_t8 = (Button) findViewById(R.id.btn_t8);
        //帮助按钮
        Button btn_help = (Button) findViewById(R.id.btn_help);
        //跳转到帮助页面
        btn_help.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startActivity(new Intent(MainActivity.this, HelpActivity.class));
            }
        });
        tvSSID = (TextView) findViewById(R.id.ssid);

    }

    /**
     * Connect click
     * wifi链接
     *
     * @param v connect button
     */
    public void onConnect(View v) {
        String text = btnConnect.getText().toString();
        if (text.equals("Connect")) {
            socketThread = new SocketThread(mainHandler, et_ip.getText().toString(), Integer.parseInt(et_port.getText().toString()));
            socketThread.start();
        } else {
            closeSocket();
        }
    }

    /**
     * Set delay time button
     * 设置延时按钮 对话框
     *
     * @param v delay button
     */
    public void onSetTime(View v) {
        showDialog(v.getId());
    }

    /**
     * Send a msg to wifi server
     * wifi 全部打开 全部关闭指令
     *
     * @param v
     */
    public void onSend(View v) {
        if (!isConnect) {
            return;
        }
        switch (v.getId()) {
            //全部打开  ff 04
            case R.id.btn_allon:
                datas[1] = (byte) 0xff;
                datas[2] = (byte) 0x04;
                break;
            //全部关闭 00 04
            case R.id.btn_alloff:
                datas[1] = (byte) 0x00;
                datas[2] = (byte) 0x04;
                break;
            default:
                break;
        }
        sendMsg();
    }

    Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                //链接成功
                case Global.MY_CONNECT_SUCCESS: {
                    isConnect = true;
                    et_ip.setEnabled(false);
                    et_port.setEnabled(false);
                    btnConnect.setText("Disconnect");
                    btnConnect.setTextColor(Color.WHITE);
                    btnConnect.setBackgroundColor(Color.GREEN);
                    datas[7] = (byte) 0x00;
                    byte[] voltage = {(byte) 0xa9, (byte) 0xaa, (byte) 0x00, datas[3], datas[4], datas[5], datas[6], datas[7]};
                    voltageSend = voltage;
                    if (isConnect)
                        sendMsg(voltage);
                    if (countDownTimer != null) {
                        countDownTimer.cancel();
                        countDownTimer = null;
                    }

                }
                break;
                //链接失败
                case Global.MY_CONNECT_FAILLY: {
                    receivedata = 0 & 0xFF;
                    //关闭设备信号（接收到我设备给手机发送的报警判断位的二级报警，计时5分钟后发出的关闭设备信号0x01，默认的发送0x00）
                    datas[7] = (byte) 0x00;
                    isConnect = false;
                    btnBatteryVolts.setText("BATTERY VOLTS _ _._ _");
                    btnBatteryVolts.setBackgroundColor(Color.GRAY);
                    btnACVolts.setText("AC VOLTS _ _ _._");
                    et_ip.setEnabled(true);
                    et_port.setEnabled(true);
                    btnConnect.setText("Connect");
                    btnConnect.setTextColor(Color.BLACK);
                    btnConnect.setBackgroundColor(Color.GRAY);
                    for (int i = 0; i < 8; i++) {
                        btns[i].setBackgroundColor(Color.GRAY);
                    }
                    if (countDownTimer != null) {
                        countDownTimer.cancel();
                        countDownTimer = null;
                    }
                    getSSID();
                }
                break;
                //接收到下位机指令   通过字符串位 1 按钮高亮 0 按钮灰色
                case Global.MY_RECEIVE_MESSAGE: {
                    byte[] read = (byte[]) msg.obj;
                    String result = Integer.toBinaryString((read[1] & 0xFF) + 0x100).substring(1);
                    e("MY_RECEIVE_MESSAGE", "result===" + result);
                    int length = result.length();
                    int i = 0;
                    //取高八位数据
                    for (; i < length && i < 8; i++) {
                        if (result.charAt(i) == '1') {
                            isHighs[i] = true;
                        } else {
                            isHighs[i] = false;
                        }
                    }
                    byte[] byteAC = {read[2], read[3]};
                    int ac = byte2int(byteAC);
                    ACVoltsValue = ac / 10.0;

                    byte[] byteDC = {read[4], read[5]};
                    int dc = byte2int(byteDC);
                    batteryVoltsValue = dc / 100.0;
                    //String ss = "send:" + read[0] + "  " + read[1] + "  " + read[2] + "  " + read[3] + "  " + read[4] + "  " + read[5] + "  " + read[6] ;
                    // Toast.makeText(context,"read"+ ss, Toast.LENGTH_SHORT).show();
                    //报警值的判断
                    isAlarmVoltage(read[6] & 0xFF);

                    mainHandler.sendEmptyMessage(Global.MY_UPDATE_VOLTS);
                }
                //更新按钮显示状态
                case Global.MY_UPDATE_BUTTON: {
                    for (i = 0; i < 8; i++) {
                        if (isHighs[i] == true) {
                            btns[i].setBackgroundColor(Color.GREEN);
                        } else {
                            btns[i].setBackgroundColor(Color.GRAY);
                        }
                    }
                }
                break;
                //更新两个按键数值
                case Global.MY_UPDATE_VOLTS: {
                    btnBatteryVolts.setText("BATTERY VOLTS " + batteryVoltsFormat.format(batteryVoltsValue));
                    btnACVolts.setText("AC VOLTS " + ACVoltsFormat.format(ACVoltsValue) + "");
                }
                break;
                //再次链接
                case Global.MY_RECONNECT: {
                    getSSID();
                    socketThread = new SocketThread(mainHandler, et_ip.getText().toString(), Integer.parseInt(et_port.getText().toString()));
                    socketThread.start();
                }
                break;

                case Global.TEST: {
                    String ss = "send:" + datas[0] + "  " + datas[1] + "  " + datas[2] + "  " + datas[3] + "  " + datas[4] + "  " + datas[5] + "  " + datas[6] + "  " + datas[7];
                    Toast.makeText(context, ss, Toast.LENGTH_LONG).show();

                }
                break;

            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        getSSID();
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver();
        //存储按钮设定值到本地文件
        saveMode2File();
        super.onDestroy();
    }

    //关闭链接
    private void closeSocket() {
        //重置接收数据区
        receivedata = 0 & 0xFF;
        if (isConnect) {
            SocketThread.socketHandler.sendEmptyMessage(Global.DISSCONNET);
        }
    }

    private void To(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 存储 按钮设置状态到本地文件
     */
    private void saveMode2File() {
        // TODO Auto-generated method stub
        Editor editor = sharedPreferences.edit();
        int i = 0;
        for (; i < 8; i++) {
            editor.putInt("sp" + i, spvalues[i] - 1);
            editor.putInt("time" + i, times[i]);
        }
        editor.putString("ip", et_ip.getText().toString());
        editor.putString("port", et_port.getText().toString());

        editor.commit();
    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                               long arg3) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.sp_1:
                spvalues[0] = spdatas[0];
                break;
            case R.id.sp_2:
                spvalues[1] = spdatas[1];
                break;
            case R.id.sp_3:
                spvalues[2] = spdatas[0];
                break;
            case R.id.sp_4:
                spvalues[3] = spdatas[0];
                break;
            case R.id.sp_5:
                spvalues[4] = spdatas[arg2];
                break;
            case R.id.sp_6:
                spvalues[5] = spdatas[arg2];
                break;
            case R.id.sp_7:
                spvalues[6] = spdatas[arg2];
                break;
            case R.id.sp_8:
                spvalues[7] = spdatas[arg2];
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
        e("tag", "Nothing to select...");
    }

    @Override
    protected Dialog onCreateDialog(final int id) {
        Builder dialog = new AlertDialog.Builder(this);
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (id == R.id.btn_allon) {
            LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialogview_double, null);
            dialog.setView(layout);
            //一级电压输入框
            et_First = (EditText) layout.findViewById(R.id.first_voltage_input);
            et_First.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            et_First.setText(first);
            et_First.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    String text = charSequence.toString();
                    if (text.contains(".")) {
                        int index = text.indexOf(".");
                        if (index + 3 < text.length()) {
                            text = text.substring(0, index + 3);
                            et_First.setText(text);
                            et_First.setSelection(text.length());
                        }
                    }

                    double value = 0.0;
                    int low = 0;
                    try {
                        value = Double.parseDouble(text);
                    } catch (Exception ex) {
                        To("Please ensure the input correct");
                    }
                    low = (int) (value * 100);
                    if (low > 2400) {
                        et_First.setText("24.00");
                    }

                }

                @Override
                public void afterTextChanged(Editable editable) {
                }
            });

            //二级电压输入框
            et_Second = (EditText) layout.findViewById(R.id.second_voltage_input);
            et_Second.setText(second);
            et_Second.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            et_Second.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    String text = charSequence.toString();
                    if (text.contains(".")) {
                        int index = text.indexOf(".");
                        if (index + 3 < text.length()) {
                            text = text.substring(0, index + 3);
                            et_Second.setText(text);
                            et_Second.setSelection(text.length());
                        }
                    }

                    double value = 0.0;
                    int low = 0;
                    try {
                        value = Double.parseDouble(text);
                    } catch (Exception ex) {
                        To("Please ensure the input correct");
                    }
                    low = (int) (value * 100);
                    if (low > 2400) {
                        et_Second.setText("24.00");
                    }

                }

                @Override
                public void afterTextChanged(Editable editable) {
                }
            });
            dialog.setTitle("Alarm Voltage Setting (number)");
            dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    first = et_First.getText().toString();
                    second = et_Second.getText().toString();
                    getFirstSencondValue(first, second);
                    Editor editor = sharedPreferences.edit();
                    editor.putString("first", et_First.getText().toString());
                    editor.putString("second", et_Second.getText().toString());
                    editor.commit();
                    byte[] voltage = {(byte) 0xa9, (byte) 0xaa, (byte) 0x00, datas[3], datas[4], datas[5], datas[6], datas[7]};
                    voltageSend = voltage;
                    if (isConnect)
                        sendMsg(voltage);

                }
            });
        } else if (id == R.id.btn_name_modification) {
            LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialogview_change_name, null);
            dialog.setView(layout);
            //一级电压输入框
            final EditText etChangeName1 = (EditText) layout.findViewById(R.id.change_input_name1);
            final EditText etChangeName2 = (EditText) layout.findViewById(R.id.change_input_name2);
            final EditText etChangeName3 = (EditText) layout.findViewById(R.id.change_input_name3);
            final EditText etChangeName4 = (EditText) layout.findViewById(R.id.change_input_name4);

            etChangeName1.setText(changeName1);
            etChangeName2.setText(changeName2);
            etChangeName3.setText(changeName3);
            etChangeName4.setText(changeName4);

            dialog.setTitle("Change Button Name");
            dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Editor editor = sharedPreferences.edit();
                    if (!UtilTool.isNull(etChangeName1.getText().toString())) {
                        changeName1 = etChangeName1.getText().toString();
                        btn_5.setText(changeName1);
                        editor.putString("changeName1", changeName1);
                    }
                    if (!UtilTool.isNull(etChangeName2.getText().toString())) {
                        changeName2 = etChangeName2.getText().toString();
                        btn_6.setText(changeName2);
                        editor.putString("changeName2", changeName2);
                    }
                    if (!UtilTool.isNull(etChangeName3.getText().toString())) {
                        changeName3 = etChangeName3.getText().toString();
                        btn_7.setText(changeName3);
                        editor.putString("changeName3", changeName3);
                    }
                    if (!UtilTool.isNull(etChangeName4.getText().toString())) {
                        changeName4 = etChangeName4.getText().toString();
                        btn_8.setText(changeName4);
                        editor.putString("changeName4", changeName4);
                    }
                    editor.commit();
                }
            });
        } else {
            LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialogview, null);
            dialog.setView(layout);
            final EditText et_search = (EditText) layout.findViewById(R.id.input);
            dialog.setTitle("Set delay time(number)");
            dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    String second = et_search.getText().toString();
                    int s = 0;
                    try {
                        s = Integer.parseInt(second);
                    } catch (Exception ex) {
                        To("Please ensure the input correct");
                    }
                    switch (id) {
                        case R.id.btn_t1:
                            btn_t1.setText(second + "s");
                            times[0] = s;
                            break;
                        case R.id.btn_t2:
                            times[1] = s;
                            btn_t2.setText(second + "s");
                            break;
                        case R.id.btn_t3:
                            times[2] = s;
                            btn_t3.setText(second + "s");
                            break;
                        case R.id.btn_t4:
                            times[3] = s;
                            btn_t4.setText(second + "s");
                            break;
                        case R.id.btn_t5:
                            times[4] = s;
                            btn_t5.setText(second + "s");
                            break;
                        case R.id.btn_t6:
                            times[5] = s;
                            btn_t6.setText(second + "s");
                            break;
                        case R.id.btn_t7:
                            times[6] = s;
                            btn_t7.setText(second + "s");
                            break;
                        case R.id.btn_t8:
                            times[7] = s;
                            btn_t8.setText(second + "s");
                            break;
                    }
                }
            });
        }
        dialog.setNegativeButton("Cancel", null);
        dialog.show();
        return super.onCreateDialog(id);
    }

    @Override
    public boolean onTouch(View arg0, MotionEvent arg1) {
        // TODO Auto-generated method stub
        if (!isConnect)
            return false;
        //0x01为T模式，0x02为m模式的开，03为L模式
        //按键1固定成T模式
        spvalues[0] = spdatas[0];
        //按键2固定成M模式
        spvalues[1] = spdatas[1];
        //按键3固定成T模式
        spvalues[2] = spdatas[0];
        //按键4固定成T模式
        spvalues[3] = spdatas[0];
        switch (arg0.getId()) {
            //run
            //按键1固定成T模式   0x01为T模式，0x02为m模式的开，03为L模式
            case R.id.btn_1: {
                datas[1] = (byte) 0x01;
                datas[2] = (byte) spvalues[0];
                OnMainTouch(0, arg1);
            }
            break;
            //Start
            //按键2固定成M模式 0x01为T模式，0x02为m模式的开，03为L模式
            case R.id.btn_2: {
                datas[1] = (byte) 0x02;
                datas[2] = (byte) spvalues[1];
                OnMainTouch(1, arg1);
            }
            break;
            //ECONOMY MODE
            //按键3固定成T模式 0x01为T模式，0x02为m模式的开，03为L模式
            case R.id.btn_3: {
                datas[1] = (byte) 0x04;//0x03
                datas[2] = (byte) spvalues[2];
                OnMainTouch(2, arg1);
            }
            break;
            //OUTLETO
            //按键4固定成T模式 0x01为T模式，0x02为m模式的开，03为L模式
            case R.id.btn_4: {
                datas[1] = (byte) 0x08;//0x04
                datas[2] = (byte) spvalues[3];
                OnMainTouch(3, arg1);
            }
            break;
            //按键5的模式和以前一样，但把名称改成ACC 1，并可以自己修改名称
            case R.id.btn_5: {
                datas[1] = (byte) 0x05;//0x05
                datas[2] = (byte) spvalues[4];
                OnMainTouch(4, arg1);
            }
            break;
            //按键6的模式和以前一样，但名称改成ACC 2，并可以自己修改名称
            case R.id.btn_6: {
                datas[1] = (byte) 0x06;//0x06
                datas[2] = (byte) spvalues[5];
                OnMainTouch(5, arg1);
            }
            break;
            //按键7的模式和以前一样，但名称改成ACC 3，并可以自己修改名称。
            case R.id.btn_7: {
                datas[1] = (byte) 0x07;//0x07
                datas[2] = (byte) spvalues[6];
                OnMainTouch(6, arg1);
            }
            break;
            //按键8的模式和以前一样，但名称改成ACC 4，并可以自己修改名称。
            case R.id.btn_8: {
                datas[1] = (byte) 0x08;//
                datas[2] = (byte) spvalues[7];
                OnMainTouch(7, arg1);
            }
            break;
        }
        return false;
    }

    private void OnMainTouch(final int position, MotionEvent arg1) {
        int var = spvalues[position];
        if (var == 1) {
            if (arg1.getAction() == KeyEvent.ACTION_DOWN) {
                //如果有设定时间
                if (times[position] != 0) {
                    //按键编号
                    datas[1] = (byte) ((position + 1) & 0xFF);
                    //延时模式
                    datas[2] = (byte) 0x05;
                } else {
                    //按键编号
                    datas[1] = (byte) ((position + 1) & 0xFF);
                    //0x01为T模式，0x02为m模式的开，03为L模式
                    datas[2] = (byte) spvalues[position];
                }
                sendMsg();
            } else if (arg1.getAction() == KeyEvent.ACTION_UP && times[position] != 0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            Thread.sleep(times[position] * 1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        datas[1] = (byte) ((position + 1) & 0xFF);
                        datas[2] = (byte) 0x15;
                        sendMsg();
                    }
                }).start();
            }
        } else if (var == 2) {
            if (arg1.getAction() == KeyEvent.ACTION_DOWN) {
                if (times[position] != 0) {
                    datas[1] = (byte) ((position + 1) & 0xFF);
                    datas[2] = (byte) 0x05;
                } else {
                    datas[1] = (byte) ((position + 1) & 0xFF);
                    datas[2] = (byte) spvalues[position];
                }
                sendMsg();
            } else if (arg1.getAction() == KeyEvent.ACTION_UP && times[position] == 0) {
                datas[1] = (byte) ((position + 1) & 0xFF);
                datas[2] = (byte) 0x12;
                sendMsg();
            } else if (arg1.getAction() == KeyEvent.ACTION_UP && times[position] != 0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            Thread.sleep(times[position] * 1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        datas[1] = (byte) ((position + 1) & 0xFF);
                        datas[2] = (byte) 0x15;
                        sendMsg();
                    }
                }).start();
            }
        } else if (var == 3) {
            // Log.e("tag", "receivedata = " + receivedata);
            if (arg1.getAction() == KeyEvent.ACTION_DOWN) {
                if (times[position] != 0) {
                    datas[1] = (byte) ((position + 1) & 0xFF);
                    datas[2] = (byte) 0x05;
                } else {
                    for (i = 0; i < 8; i++) {
                        if (spvalues[i] == 3 && times[i] == 0) {
                            receivedata &= ~(((byte) 0x01 << i) & 0xFF);
                            //  e("tag", "i=============" + i);
                            isHighs[7 - i] = false;
                        }
                    }
                    // e("tag", "position = " + position);
                    isHighs[7 - position] = true;
                    receivedata |= ((byte) 0x01 << position);
                    mainHandler.sendEmptyMessage(Global.MY_UPDATE_BUTTON);
                    //  e("tag", "receivedata222 = " + receivedata);
                    datas[1] = (byte) receivedata;
                    datas[2] = (byte) spvalues[position];
                }
                sendMsg();
            } else if (arg1.getAction() == KeyEvent.ACTION_UP && times[position] != 0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            Thread.sleep(times[position] * 1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        datas[1] = (byte) ((position + 1) & 0xFF);
                        datas[2] = (byte) 0x15;
                        sendMsg();
                    }
                }).start();
            }
        }
    }

    //通过wifi发送数据 主要方法
    private void sendMsg() {
        e("tag", "datas = " + datas[0] + "  " + datas[1] + "  " + datas[2] + "  " + datas[3] + "  " + datas[4] + "  " + datas[5] + "  " + datas[6] + "  " + datas[7]);
        StringBuffer read2 = new StringBuffer();
        for (int t = 0; t < datas.length; t++) {
            char s = (char) datas[t];
            int jh = s;
            read2.append(",0x");
            read2.append(Integer.toHexString(jh));
        }
        // e("tag", "send = " + read2.toString());
        //mainHandler.sendEmptyMessage(Global.TEST);
        Message msg = SocketThread.socketHandler.obtainMessage(Global.SEND_MESSAGE);
        msg.obj = datas;
        SocketThread.socketHandler.sendMessage(msg);
    }

    //发送一级二级报警电压参数给下位机
    private void sendMsg(byte[] voltage) {
        //Log.e("tag", "datas = " + datas[0] + "  " + datas[1]+ "  " + datas[2]+ "  " + datas[3]+ "  " + datas[4]+ "  " + datas[5]+ "  " + datas[6]+ "  " + datas[7]);
        StringBuffer read2 = new StringBuffer();
        for (int t = 0; t < voltage.length; t++) {
            char s = (char) voltage[t];
            int jh = s;
            read2.append(",0x");
            read2.append(Integer.toHexString(jh));
        }
        // e("tag", "send voltage= " + read2.toString());
        Message msg = SocketThread.socketHandler.obtainMessage(Global.SEND_MESSAGE);
        msg.obj = voltage;
        SocketThread.socketHandler.sendMessage(msg);
    }

    //获取一级报警二级报警电压的高位低位
    private void getFirstSencondValue(String first, String second) {
        byte[] firstByte = {0, 0};
        byte[] secondByte = {0, 0};
        firstByte = getDcValue(first, 1);
        secondByte = getDcValue(second, 2);
        datas[3] = firstByte[0];
        datas[4] = firstByte[1];
        datas[5] = secondByte[0];
        datas[6] = secondByte[1];


    }


    //获取设置电压高位和低位  is1Or2==1 一级报警值  ==2 二级报警值
    private byte[] getDcValue(String dc, int is1Or2) {
        byte[] result = {0, 0};
        if (dc.equals("0"))
            return result;

        double value = 0.0;
        int low = 0;
        try {
            value = Double.parseDouble(dc);
        } catch (Exception ex) {
            To("Please ensure the input correct");
        }
        low = (int) (value * 100);
        if (is1Or2 == 1)
            alarmVoltage1 = low;
        else
            alarmVoltage2 = low;
        result = int2byte(low);
        return result;
    }

    public static byte[] int2byte(int res) {
        byte[] targets = new byte[2];
        targets[0] = (byte) ((res >> 8) & 0xff);// 电压高位
        targets[1] = (byte) (res & 0xff);// 电压低位
        return targets;
    }

    public static int byte2int(byte[] res) {
        // 一个byte数据左移24位变成0x??000000，再右移8位变成0x00??0000
        int targets = (res[1] & 0xff) | ((res[0] << 8) & 0xff00); // | 表示安位或
        return targets;
    }

    //判断是否属于报警状态
    private void isAlarmVoltage(int dcValue) {
        if (dcValue == 0) {
            btnBatteryVolts.setBackgroundColor(Color.GRAY);
        }
        //一级报警
        if (dcValue == 1) {
            btnBatteryVolts.setBackgroundColor(Color.RED);
        }
        //二级报警
        if (dcValue == 2) {
            btnBatteryVolts.setBackgroundColor(Color.RED);
            if (countDownTimer != null)
                return;
            countDownTimer = new CountDownTimer(5 * 60 * 1000, 1000) {
                public void onTick(long millisUntilFinished) {
                    //  Toast.makeText(context,"倒计时"+millisUntilFinished / 1000 + "S", Toast.LENGTH_LONG).show();

                }

                public void onFinish() {
                    //关闭设备信号（接收到我设备给手机发送的报警判断位的二级报警，计时5分钟后发出的关闭设备信号0x01，默认的发送0x00）
                    datas[1] = (byte) 0xaa;
                    datas[2] = (byte) 0x00;
                    datas[7] = (byte) 0x01;
                    //   String ss = "send:" + datas[0] + "  " + datas[1] + "  " + datas[2] + "  " + datas[3] + "  " + datas[4] + "  " + datas[5] + "  " + datas[6] + "  " + datas[7];
                    //   Toast.makeText(context,"AlarmVoltage"+ ss, Toast.LENGTH_LONG).show();
                    sendMsg();

                }
            }.start();
        } else if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
            //关闭设备信号（接收到我设备给手机发送的报警判断位的二级报警，计时5分钟后发出的关闭设备信号0x01，默认的发送0x00）
            datas[7] = (byte) 0x00;
            //Toast.makeText(context,"倒计时取消重新来~~~~~~~~~~", Toast.LENGTH_LONG).show();
        }
    }
    //获取wifi SSID
    private void getSSID() {
        WifiInfo wifiInfo; wifiInfo = wifiManager.getConnectionInfo();
       final String wifiId = wifiInfo != null ? wifiInfo.getSSID() : null;
        if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            if (wifiId != null)
                tvSSID.setText("SSID:" + wifiId.substring(1,(wifiId.length()-1)));
        } else
            tvSSID.setText("SSID:");
    }
    private  void registerReceiver(){
        IntentFilter filter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(myReceiver, filter);
    }
    private  void unregisterReceiver(){
        this.unregisterReceiver(myReceiver);
    }
    private BroadcastReceiver myReceiver=new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifiNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (!wifiNetInfo.isConnected()) {
                getSSID();
            }else {
                getSSID();
            }
        }
    };
}
